
import { ref, reactive, toRefs, onMounted, onUnmounted } from 'vue'
import { useResizeObserver } from '@vueuse/core'
import { useAccidentTableList } from '@/store';
import * as echarts from 'echarts'
import * as DashboardApi from "@/service/api/dashboard";
// 大队事故分析
import getGroupBarChartOption from './data/bar.chart.js'
// 事故高发路段排行
import getTopRankBarChartOption from './data/top-rank.bar.chart.js'
const tableList = useAccidentTableList()

/**
 * @description: 24小时事故、关注事故、历史事故
 * @return {*}
 */
export function useAccidentPannelInfo() {
  const pannelInfoModel = reactive({ dialogVisible: false, dialogInfo: {}, activeTab: 2, fullDayData: [], historyData: [], isEmptyFullDay: false, isEmptyHistory: false })
  const pannelTabs = [{ name: '历史事故', type: 2 },{ name: '24小时事故', type: 1 }]

  async function getHomeAccidentInfoData() {
    const fullDayData = await DashboardApi.GetHomeAccidentInfo({ type: 1 })
    const historyData = await DashboardApi.GetHomeAccidentInfo({ type: 2 })
    if (fullDayData?.length) {
      pannelInfoModel.fullDayData = fullDayData
    } else {
      pannelInfoModel.isEmptyFullDay = true
    }
    if (historyData?.length) {
      pannelInfoModel.historyData = historyData
    } else {
      pannelInfoModel.isEmptyHistory = true
    }
  }


  function onInfoPannelClick(info) {
    pannelInfoModel.dialogInfo = info
    pannelInfoModel.dialogVisible = true
  }


  return {
    pannelTabs,
    ...toRefs(pannelInfoModel),
    getHomeAccidentInfoData,
    onInfoPannelClick
  }

}

/**
 * @description: 大队事故分析
 * @return {*}
 */
export function useAccidentGroupBarChart() {
  const groupBarRef = ref(null)
  const isEmptyGroupChart = ref(false)
  let barChartInstance = null // 新增点击处理函数
  const handleBarClick = async (params) => {
    const seriesName = params.seriesName
    const dataIndex = params.dataIndex
    const deptName = barChartInstance.getOption().xAxis[0].data[dataIndex]
    const currentValue = barChartInstance.getOption().series[0].data[dataIndex]
    const compareValue = barChartInstance.getOption().series[1].data[dataIndex]
    if (deptName === undefined) return
    let param1 = {
      pageNum: '1',
      pageSize: currentValue,
      flag: 'today',
      dept: deptName,
    }
    let param2 = {
      pageNum: '1',
      pageSize: compareValue,
      flag: 'yesterday',
      dept: deptName,
    }
    const res1 = await DashboardApi.GetHomedeptPageInfo(param1)
    const res2 = await DashboardApi.GetHomedeptPageInfo(param2)
    tableList.setDaDuiShiGuShu(true, deptName, res1.rows, res2.rows)

  }
  async function getHomeAccidentBarChartData() {
    const data = await DashboardApi.GetHomeAccidentGroupBarChartData()
    const { compare, current } = data || {}

    if (compare?.length && current?.length) {
      const option = getGroupBarChartOption(data)
      setChartOption(option)

      // 确保事件监听只注册一次
      barChartInstance.off('click') // 先移除旧监听
      barChartInstance.on('click', handleBarClick)
    } else {
      isEmptyGroupChart.value = true
    }
  }

  function setChartOption(option) {
    barChartInstance.setOption(option)
  }
  onMounted(() => {
    barChartInstance = echarts.init(groupBarRef.value)
    getHomeAccidentBarChartData()
  })


  return {
    isEmptyGroupChart,
    groupBarRef,
    handleBarClick
  }
}

/**
 * @description: 事故高发路段排行
 * @return {*}
 */
export function useAccidentTopRankBarChart() {

  let rowsModel = {
    total: [],
    rank: [],
    roads: [],
    grayBar: []
  }

  let currentIndex = 0
  const length = 6

  const rankBarRef = ref(null)
  const isEmptyRankChart = ref(false)
  let barChartInstance = null
  let timer = null
  let timer2 = null
  function sliceArray(array, start, length) {
    return array.slice(start, start + length)
  }

  function makeRangeData() {

    const rangeData = {
      total: rowsModel.total,
      barData: sliceArray(rowsModel.total, currentIndex, length).reverse(),
      roads: sliceArray(rowsModel.roads, currentIndex, length).reverse(),
      rank: sliceArray(rowsModel.rank, currentIndex, length).reverse(),
      grayBar: rowsModel.grayBar
    }
    return rangeData
  }

  const handleBarClick1 = async (params) => {
    if (!barChartInstance || !params?.dataIndex) return

    try {
      const option = barChartInstance.getOption()
      const deptName = option.yAxis[0]?.data?.[params.dataIndex]
      const compareValue = option.series[1]?.data?.[params.dataIndex]
      const res = await DashboardApi.GetHomeroadPageInfo({
        pageNum: '1',
        pageSize: compareValue,
        road: deptName
      })
      tableList.setShiGuGaoFaLuDuan(true, deptName, res.rows)
    } catch (error) {
      console.error('图表点击处理异常:', error)
    }
  }
  async function getHomeAccidentBarChartData() {
    const data = await DashboardApi.GetHomeAccidentTopRankBarChartData()
    rowsModel.roads = []
    rowsModel.total = []
    rowsModel.rank = []
    rowsModel.grayBar = []

    currentIndex = 0
    if (data) {
      const rows = data

      for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        rowsModel.roads.push(row.roadName)
        rowsModel.total.push(row.count)
        rowsModel.rank.push(i + 1)
      }

      rowsModel.grayBar = new Array(6).fill(Math.max(...rowsModel.total) + 5)
      const rangeData = makeRangeData()
      const option = getTopRankBarChartOption(rangeData)
      setChartOption(option)

      // 新增事件绑定 ↓
      barChartInstance.off('click') // 先移除旧监听
      barChartInstance.on('click', handleBarClick1)

      initInterval(rows)
    } else {
      isEmptyRankChart.value = true
    }

  }

  function initInterval(rows) {

    clearInterval(timer);
    timer = setInterval(() => {

      const rangeData = makeRangeData()
      const option = getTopRankBarChartOption(rangeData)
      setChartOption(option)

      // 更新起始索引
      currentIndex++;
      if (currentIndex + length > rows.length) {
        currentIndex = 0
      }
    }, 2000);
  }

  function setChartOption(option) {
    barChartInstance.setOption(option)
  }

  useResizeObserver(rankBarRef, () => {
    if (barChartInstance) {
      barChartInstance.resize()
    }
  })



  onMounted(() => {
    barChartInstance = echarts.init(rankBarRef.value)
    getHomeAccidentBarChartData()

    timer2 = setInterval(() => {
      getHomeAccidentBarChartData()
    }, 1000 * 60 * 30)
  })

  onUnmounted(() => {
    clearInterval(timer);
    clearInterval(timer2);
  })

  return {
    isEmptyRankChart,
    rankBarRef,
    handleBarClick1
  }
}
